const app = getApp();
const api = require('../../../ws_micro_shop/utils/api.js');
const { qyWXCheckSeesion } = require('../../../common/utils/ws/ws-wxwork');
const { throttle } = require('../../common/utils/util');


Page({
  data: {
    current: 0,
    tabs: ['消费回访', '流失回访'],
    list: [],
    keyword: '',
    canPullUp: true,
    page: 1,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-15.png',
      text: '暂时没有客户',
    },
    isData: false,
    isShowMask: false,
    followUpText: '',
    customerId: '',
    isEmpty: true,
  },

  onLoad() {
    let { current = '' } = this.options;

    this.setData({
      isData: false,
      from_openid: app.ws_micro_shop_globalData.openid,
      current: Number(current),
      isSaas: app.ws_micro_shop_globalData.isSaas,
    }, () => {
      this.getList();
    });
  },

  onTabs(e) {
    const { current } = e.currentTarget.dataset;
    this.setData(
      {
        current,
        canPullUp: true,
        page: 1,
        list: [],
        isData:false,
      },
      () => {
        this.getList();
      },
    );
  },

  getList() {
    let { current: customer_type, keyword: key_words, list, page } = this.data;
    wx.showLoading({
      title: '正在加载',
    });
    app.ws_micro_shoprequest({
      url: api.staff.cunstomer,
      data: {
        keywords: key_words,
        customer_type,
        page,
      },
      success: res => {
        if (res && res.code === 0 && res.data) {
          const newList = res.data;
          if (newList.length <= 0) {
            this.setData({
              canPullUp: false,
              isData: true,
            });
            return;
          }

          list = [...list, ...newList];

          this.setData({
            list,
            isData: true,
          });
        }
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },

  inputSearch() {
    this.setData(
      {
        list:[],
        page: 1,
      },
      () => {
        this.getList();
      },
    );
  },

  clearTxt() {
    this.setData({
      keyword: '',
      page: 1,
      list: [],
      isEmpty: true,
    }, () => {
      this.getList();
    });
  },

  onInput(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      keyword: e.detail.value,
    });
  },

  openChat(e) {
    const {
      wechat_open_id: uid = '',
      nickname = '',
      realname = '',
      external_userid: externalUserId = '',
    } = e.currentTarget.dataset.item;

    if (!app.isWXWork) {
      this.toLeaveMessage(uid,nickname,realname);
      return;
    }

    qyWXCheckSeesion({
      success: () => {
        if (externalUserId) {
          wx.qy.openEnterpriseChat({
            externalUserIds: externalUserId,
            groupName: '',
            success: () => {
              console.log('enterprise chat opened');
            },
          });
        } else {
          this.toLeaveMessage(uid,nickname,realname);
        }
      },
      fail: err => {
        console.log('企业微信登录失败', err);
      },
    });
  },

  onNavite:throttle(function(e) {
    const { url, ...params } = e.currentTarget.dataset;
    url && app.util.navigateTo(url, params);
  }),

  onReachBottom() {
    let { canPullUp, page } = this.data;
    if (canPullUp) {
      this.setData({
        page: ++page,
      });

      this.getList();
    }
  },

  toLeaveMessage(uid = '',nickname = '',realname = '') {
    const { from_openid = '' } = this.data;
    const url = `/ws_micro_shop_guide/pages/message/detail/detail?from_openid=${from_openid}&to_openid=${uid}&name=${nickname ||
      realname}`;
    app.util.navigateTo(url);
  },

  onMore(e) {
    wx.showActionSheet({
      itemList: ['拨打电话', '添加跟进'],
      success: res => {
        console.log(res);
        const tapIndex = res.tapIndex;
        const { mobile: phoneNumber = '', uid: customerId = '' } = e.currentTarget.dataset.item;
        switch (Number(tapIndex)) {
          case 0:
            phoneNumber &&
              wx.makePhoneCall({
                phoneNumber,
              });
              phoneNumber || wx.showToast({
                title: '该客户尚未录入联系方式',
                icon: 'none',
              })
            break;
          case 1:
            this.setData({
              // isShowMask: true,
              customerId,
            });
            let url = '/ws_micro_shop_guide/pages/record/record';
            app.util.navigateTo(url, { type: 'addFollow', id: customerId });
            break;
  }
      },
    });
  },

  onAddFollowUp() {
    const { customerId: customer_id = '', followUpText: content } = this.data;
    app.ws_micro_shoprequest({
      url: api.staff.edit_followup,
      data: {
        content,
        customer_id,
      },
      method: 'post',
      success: res => {
        if (res.code === 0) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            mask: true,
            duration: 1500,
            success: res => {
              this.onMask();
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            mask: true,
            duration: 1500,
          });
        }
      },
    });
  },

  setFollowUpText(e) {
    this.setData({
      followUpText: e.detail.value,
    });
  },

  onMask() {
    const { isShowMask } = this.data;

    this.setData({
      isShowMask: !isShowMask,
    });
  },
});
